var dl_manager = liwe.module ( 'dl_manager' );

//dl_manager instances' core
function DLCore ( name, attrs )
{
	this.name 			= name;
	this.tmpl_mod 			= attrs.get ( 'templates', 'dl_manager' );//module name form which templates will be inherited
	this.dest_div	 		= attrs.get ( 'dest_div', dl_manager.dest_div );
	this.module 			= attrs.get ( 'module', 'dl_manager' );
	this.id_obj 			= attrs.get ( 'id_obj', 0 );
	this.filter_form_id 		= attrs.get ( 'filter_form_id', name + ':' + dl_manager.filter_form_id );		// id div
	this.upload_form_id 		= attrs.get ( 'upload_form_id', name + ':' + dl_manager.upload_form_id );		// id div
	this.edit_form_id 		= attrs.get ( 'edit_form_id', name + ':' + dl_manager.edit_form_id );			// id div
	this.browse_option_form_id 	= attrs.get ( 'browse_option_form_id', name + ':' + dl_manager.browse_option_form_id ); // id div
	this.edit_form_name 		= this.edit_form_id + ':form';	 							// id form
	this.upload_form_name 		= this.upload_form_id + ':form';							// id form
	this.filter_form_name 		= this.filter_form_id + ':form';							// id form
	this.browse_option_form		= this.browse_option_form_id + ':name';							// id form
	this.div_prefix 		=  attrs.get ( 'div_prefix', name + ':DLM' );
	//cbacks 
	this.cbacks = {
			'after_init' 	: attrs.get ( 'after_init', null ),
			'pre_render' 	: attrs.get ( 'pre_render', null ),
			'post_render' 	: attrs.get ( 'post_render', null ),
			'image_click' 	: attrs.get ( 'image_click', null ),
			'row_manip' 	: attrs.get ( 'row_manip', dl_manager._row_manip ),
			'filter_form'	: attrs.get ( 'filter_form', dl_manager.filter_form )
			};
	/*
	if ( dl_manager.get ( 'admin' ) )
	{
	*/
			this.cbacks [ 'upload_form' ] 	= attrs.get ( 'upload_form', dl_manager.admin.upload_form );
			this.cbacks [ 'edit_form' ]	= attrs.get ( 'edit_form', dl_manager.admin.edit_form );
	//}

	this.browse_options = {
				'order_by' : 'name',
				'page_view' : 'icon',
				'lines_per_page' : 10	
				};
	//internals
	this._tmpl_ready = false;
	this._retry = 0;
	this._sidebar_div = this.div_prefix + '-sidebar';
	this._topbar_div  = this.div_prefix + '-topbar';
	this._browser_div = this.div_prefix + '-browser';
	this._results_div = this.div_prefix + '-results';

	this._browse_files_params = {};
	this._curr_tmpl = {};
	//init instance dataset
	this._init_ds = function ()
	{
		this.ds = new DataSet ( 'ds:' + this.name );
		this.ds._DLM = this.name;
		this.ds.cbacks [ 'row_manip' ] = this.cbacks [ 'row_manip' ];
	};
	//get assigned templates
	//NOTE: all this should be instantaneous using cached templates 
	this.grab_templates = function ( tmpl_mod, cback )
	{
		if ( this.retry > 5 ) return;
		if ( ! window [ tmpl_mod ] || ! window [ tmpl_mod ][ 'templates' ] )
		{ 
			var self = this;
			setTimeout ( function () { self.grab_templates ( tmpl_mod, cback ); }, 200 );
			this.retry ++;
		}
		
		this.templates = window [ tmpl_mod ][ 'templates' ];
		if ( tmpl_mod != 'dl_manager' )
		{
			//if custom templates, merge them with default values
			this.templates = dl_manager._merge_templates ( this.templates );
		}
		this.retry = 0;
		this._tmpl_ready = true;
		if ( cback ) cback ( this );
	};

	//var self = this;
	this.grab_templates ( this.tmpl_mod, function ( self )
		{
		 	self._init_ds ();
			dl_manager._instances [ self.name ] = self;
			if ( self.cbacks [ 'after_init' ] ) self.cbacks [ 'after_init' ] ( self );
			return self;
		} );
};

//path to media folder
dl_manager.file_base_path = '/site/dl_manager/';
dl_manager._instances = {};
dl_manager._def_tmpl = { 
		'list': {
			'open' 		: 'DLM-table-open',
			'close'		: 'DLM-table-close',
			'header' 	: 'DLM-details-head',
			'no-rows' 	: 'DLM-ds-list-no-rows',
			'open-row' 	: 'DLM-row-open',
			'close-row'	: 'DLM-row-close',
			'row'  		: 'DLM-cell-details'
			},
		'icon': {
			'open' 		: 'DLM-div-open',
			'close'		: 'DLM-div-close',
			'header' 	: '',
			'no-rows' 	: 'DLM-ds-icon-no-rows',
			'open-row' 	: 'DLM-ds-icon-row-open',
			'close-row'	: 'DLM-ds-icon-row-close',
			'row'  		: 'DLM-cell-icon'
			},
		'full' : {
			'open' 		: 'DLM-table-open',
			'close'		: 'DLM-table-close',
			'header' 	: 'DLM-full-details-head',
			'no-rows' 	: 'DLM-ds-full-no-rows',
			'open-row' 	: 'DLM-row-open',
			'close-row'	: 'DLM-row-close',
			'row'  		: 'DLM-cell-full-details'
			},
		'paginator' : {
			'pag-first' 	: 'DLM-pag-first' , 
			'pag-last' 	: 'DLM-pag-last' , 
			'pag-prev' 	: 'DLM-pag-prev' , 
			'pag-next' 	: 'DLM-pag-next'  
			}
		};

dl_manager._ext_list 		= [];
dl_manager._mods_list 		= [];

dl_manager.filter_form_id 	= 'DLM-filter-form';
dl_manager.edit_form_id 	= 'DLM-edit-form';
dl_manager.upload_form_id 	= 'DLM-upload-form';
dl_manager.browse_option_form_id= 'DLM-browse-option-form';

//init dl_manager instance
dl_manager.init_instance = function ( name, attrs )
{
	var inst = new DLCore ( name, attrs );
	return inst;
};
//get given name instance
dl_manager.get_instance = function ( name )
{
	inst = dl_manager._instances.get ( name );
	return inst;
};

dl_manager._get_ext_list = function ( cback )
{
	dl_manager.ajax ( { "action" : "dl_manager.ajax._get_ext_list" }, function ( data )
                                        {
						dl_manager._ext_list.push ( { label : "" , value : "" } );
                                                data [ 'ext_list' ].iterate ( function ( v, k )
										{
											 dl_manager._ext_list.push ( { label : v [ 'fext' ] , value : v [ 'fext' ] } );
										}
									     );
						if ( cback ) cback ();
                                        });
	
};

dl_manager._get_mods_list = function ( name, cback )
{
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;
	inst._mods_list = [];
	var ck_curr_mudule = false;
	var mod, curr = inst.module;

	function _loop_mods ( mods )
	{
		mods.iterate ( function ( v )
			{
				mod = v [ 'module' ];
				if ( !mod || mod == curr || mod == 'dl_manager' ) return;
				dl_manager._mods_list.push ( { label : mod , value : mod } );
			} );
		dl_manager._mods_list.push ( { label : "dl_manager" , value : "dl_manager" } );
		if ( curr != 'dl_manager' && curr != '' ) dl_manager._mods_list.push ( { label : curr, value : curr } );
		if ( cback ) cback ();
	}
	dl_manager.ajax ( { "action" : "dl_manager.ajax._get_mods_list" }, function ( data )
		{
			_loop_mods ( data [ 'mods_list' ] );
		});
};

dl_manager._get_options = function ( name, cback )
{
	dl_manager._get_mods_list ( name, function () 
			{ 
				dl_manager._get_ext_list ( cback );
			} );
};

/*
merge custom templates values with default values. 
In this way is possibile to define as custom templates
just a subset of values
*/
dl_manager._merge_templates = function ( tmpl )
{
	//loop through default structure and values
	var def = dl_manager._def_tmpl;
	def.iterate ( function ( keys, view )
		{
			//loop through templates keys
			keys.iterate ( function ( tmpl_key, k )
				{
					//merge default values with module specific ones
					tmpl [ tmpl_key ] = tmpl.get ( tmpl_key, dl_manager.templates [ tmpl_key ] );
				} );
		} );
	//return merged values 
	return tmpl;
};

/*assign selected view templates to instance dataset*/
dl_manager.set_ds_templates = function ( name )
{
	function _build_row ()
	{
		var buf = new String.buffer ();
		buf.add ( templates [ v [ 'open-row' ] ] ); 
		buf.add ( templates [ v [ 'row' ] ] ); 
		buf.add ( templates [ v [ 'close-row' ] ] ); 
		return buf.toString ();
	};
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;
	var ds = inst [ 'ds' ];
	var view = inst [ 'browse_options' ][ 'page_view' ];
	var templates = inst [ 'templates' ];
	var view_tmpl = dl_manager._def_tmpl;
	var v = view_tmpl [ view ];
	//set templates to dataset
	ds.paginator.templates [ 'pag-first' ]	= templates [ view_tmpl [ 'paginator' ][ 'pag-first' ] ]; 
	ds.paginator.templates [ 'pag-last' ]	= templates [ view_tmpl [ 'paginator' ][ 'pag-last' ] ]; 
	ds.paginator.templates [ 'pag-prev' ]	= templates [ view_tmpl [ 'paginator' ][ 'pag-prev' ] ]; 
	ds.paginator.templates [ 'pag-next' ]	= templates [ view_tmpl [ 'paginator' ][ 'pag-next' ] ]; 
	ds.paginator.templates [ 'pag-pos' ]	= '%(_PAGE)s';
	ds.paginator.templates [ 'pag-sep' ]	= '';

	ds.templates [ 'table_start' ]	= templates [ v [ 'open' ] ];  
	ds.templates [ 'table_end' ]	= templates [ v [ 'close' ] ];  
	ds.templates [ 'table_header' ]	= templates [ v [ 'header' ] ];  
	ds.templates [ 'table_footer' ]	= templates [ v [ 'footer' ] ];  
        ds.templates [ 'no_rows' ]	= templates [ v [ 'no-rows' ] ];  
        ds.templates [ 'table_row' ]	= _build_row (); 
};

/*init interface tabs*/	
dl_manager._init_tabs = function ( name )
{
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;
	var s = new String.buffer ();
	var res, prefix = name + '-DLM-tabs';
	dest_div = name + ':DLM-filter-form-cnt';

	if ( ! inst.tabs ) inst.tabs = new OS3Tabs.instance ( prefix );

	var filter_name = inst.filter_form_id;//name + ":filter-form";
	var upload_name = inst.upload_form_id;//name + ":upload-form";

	inst.tabs.clear ();

	inst.tabs.set_group ( name + '-DLM-tabs' );

	$( dest_div, 'Initializing tabs ...' );
	s.add ( String.formatDict ( dl_manager.templates [ 'tabs_start' ], { 'prefix' : prefix  } ) );

	s.add ( String.formatDict ( dl_manager.templates [ 'tabs_tab' ], { "tab_name" : filter_name } ) );
	inst.tabs.add ( 'Filter', filter_name );

	if ( dl_manager.get ( 'admin' ) )
	{
		s.add ( String.formatDict ( dl_manager.templates [ 'tabs_tab' ], { "tab_name" : upload_name } ) );
		inst.tabs.add ( 'Upload', upload_name );
	}

	s.add ( dl_manager.templates [ 'tabs_end' ] ); 

	res = s.toString ();

	$( dest_div, res );

	inst.tabs.render ();

	if ( dl_manager.get ( 'admin' ) ) inst.tabs.enable_tab ( upload_name, 'enabled' );
	inst.tabs.enable_tab ( filter_name, 'enabled' );
	inst.tabs.send_event ( filter_name, 'click' );
};

dl_manager.set_module = function ( name, module )
{
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;
	inst.module = module;
};

/* dl_manager.set_pagination ();
	param: name ( string ) 	instance name
	param: val (int)	number of results per page
	return: nothing
	set pagination var and call browse_files function ( do we need it ?? )
*/
dl_manager.set_pagination = function ( name, val )
{
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;
	inst.browse_options [ 'lines_per_page' ] = val || 10;
	dl_manager.update_view ( name, no_browse );
};

/* dl_manager.set_page_view ();
	param: name ( string ) 	instance name
	param: val ( string ) 	type of view  (values: icons,details )
	return: nothing
*/
dl_manager.set_page_view = function ( name, val, no_browse )
{
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;
	
	inst.browse_options [ 'page_view' ] = val || 'icon';
	dl_manager.set_ds_templates ( name );	
	dl_manager.update_view ( name, no_browse );
};
/* dl_manager.set_order_by ();
	param: name ( string ) 	instance name
	param: val ( string ) 	order by  (values: name,fext,created )
	return: nothing
	set order by preference 
*/
dl_manager.set_order_by = function ( name, val )
{
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;
	inst.browse_options [ 'order_by' ] = val || 'name';
	dl_manager.update_view ( name, no_browse );
};

/* dl_manager.update_view ()
	param: no_browse
	refresh results view
*/
dl_manager.update_view = function ( name, no_browse )
{
	if ( no_browse ) return;
	dl_manager.browse_files ( name ); 
};

/* dl_manager.filter_form ();
	name: instance name ( string )	
	return: nothing
	Create filter form for searching otpions
*/
dl_manager.filter_form = function ( name, dest_div ) 
{
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;
	if ( ! dest_div ) dest_div = inst.filter_form_id;
	//if ( ! dest_div ) dest_div = name + ':DLM-filter-form';
	var f = new liwe.form.instance ( inst.filter_form_name );
	// create filter form
        //f.hidden ( "module", this._module );
	f.select ( { name: "module", options: dl_manager._mods_list, force_select: false, style: "width:150px;", value: inst [ 'module' ] , onchange: "dl_manager.set_module ( '" + name + "', this.value );" } );
        f.hidden ( "id_obj", inst [ 'id_obj' ] );
        f.hidden ( "inst", name );
	f.label ( { value: "Nome file" } );
        f.text   ( { name: "name", maxlength: 200 } );
	f.label ( { value: "Descrizione" } );
        f.text   ( { name: "descr", maxlength: 200 } );
	f.label ( { value: "Estensione" } );
	f.select ( { name: "fext", options: dl_manager._ext_list, force_select: false, style: "width:150px;" } );
	f.label ( { value: "Tags" } );
        f.tags   ( { name: "filters_tags", module: 'dl_manager', size: '20' } ); 
        f.button ( { value: "Cerca", 'class': 'green', onclick: "dl_manager.browse_files( '" + inst.name + "' );" } );
        f.button ( { value: "Reset", 'class': 'yellow', onclick: "dl_manager.reset_form( '" + inst.filter_form_name + "' );" } );

        f.set ( dest_div );
};

/* dl_manager.browse_option ();
	param: name 			name of instance
	param: dest_div ( string )	destination div
	return: nothing
	Create filter form for browsing options ( pagination, sorting etc )
*/
dl_manager.browse_option = function ( name, dest_div )
{
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;
	if ( ! dest_div ) dest_div = inst._topbar_div;
	//if ( ! dest_div ) dest_div = name + ':DLM-topbar';

	var f = new liwe.form.instance ( inst.browse_option_form );

	var pagination_opts = [
				{ label: "10",	value: "10" },
				{ label: "20",	value: "20" },
				{ label: "30",	value: "30" },
				{ label: "*",	value: ">" }
			      ];
	f.select ( { label: "per page", name: "pagination", options: pagination_opts, force_select: false, nonl: true, onchange: 'dl_manager.set_pagination ( \''+ inst.name + '\', this.value );' } );

	var view_opts = [
			 { label: "icone", 	value: "icon" },
			 { label: "lista", 	value: "list" },
			 { label: "dettagli", 	value: "full" }
		        ];

	f.select ( { label: "page view", name: "page_view", options: view_opts, force_select: false, nonl: true, onchange: 'dl_manager.set_page_view ( \''+ inst.name + '\', this.value );' } );
	
	var order_opts = [
			 { label: "nome", 	value: "name" },
			 { label: "estensione", value: "fext" },
			 { label: "creato", 	value: "created" }
		        ];

	f.select ( { label: "ordinamento", name: "order_by", options: order_opts, force_select: false, nonl: true, onchange: 'dl_manager.set_order_by (  \''+ inst.name + '\', this.value );' } );
	//f.button ( { label: "upload", value: "upload", onclick : "DownloadManager.prototype.admin.upload_form ( 'DM-upload-form' );" } );

	f.set ( dest_div );
};

/* dl_manager.reset_form ();
	param: form_id ( string )	
	return: nothing
	generic function to clear form values
*/
dl_manager.reset_form = function ( form_id ) 
{
	var frm = liwe.form.get ( form_id );
	frm.clear ();
};

/* dl_manager.render ();
	param: dest_div ( string )	destination div for DLM ( mandatory )
	param: module ( string )	module name
	return: nothing		
*/
dl_manager.render = function ( name, attrs )
{	
	var inst = dl_manager.get_instance ( name );
	if ( ! inst )
	{
		if ( ! attrs ) attrs = {};
		attrs [ 'after_init' ] = attrs.get ( 'after_init', function ( obj ) { dl_manager.render ( name, attrs ); } ); 
		dl_manager.init_instance ( name , attrs ); 	
		return;
	}
	var curr_module = inst.module;
	var dest_div = inst.dest_div;
	if ( inst.cbacks.get ( 'pre_render' ) ) inst.cbacks [ 'pre_render' ] ();
	// check if select options values have been loaded
	dl_manager._get_options ( name, function ()
		{
			// create interface throught templates
			var layout = String.formatDict ( dl_manager.templates [ "interface" ], { 'name' : name } );
			$( dest_div , layout ); 
			dl_manager._init_tabs ( name );
			// assign interface contents
			dl_manager.browse_option ( name, inst._topbar_div );
			// sidebar elements
			inst.cbacks [ 'filter_form' ] ( name );
			if ( dl_manager.get ( 'admin' ) ) inst.cbacks [ 'upload_form' ] ( name, dest_div );
			if ( inst.cbacks.get ( 'post_render' ) ) inst.cbacks [ 'post_render' ] ();
		} );
};


/* dl_manager._row_manip ();
	param: ds ( object )		dataset
	param: row ( object ) 		current row
*/
dl_manager._row_manip = function ( ds, row )
{
	/* row response
	"name": "Firefox_wallpaper.png", "descr": "", "fext": "png", "created": "2010-08-31 12:03:43", 
	"_pos": 0, "id": 1
	*/
	//FIXME: get dir path from ajax request
	var main_dir = String.format ( "%3.3d" , row [ 'id' ] , 1000 );
	var sub_dir = String.format ( "%2.2d" , row [ 'id' ] , 100 );
	var file_path = String.format ( "%s%s/%s/", dl_manager.file_base_path, main_dir, sub_dir );

	row [ "thumb_path" ] = row [ 'path' ] + "/";
	row [ "thumb_name" ] =  row [ 'id' ];
	row [ "thumb_ext" ]  =  'jpg';

	var file_path = row [ "thumb_path" ] + row [ "name" ];
	var file_id_path = String.format ( "%s%s%s%s" , row [ "thumb_path" ] , row [ "id" ] , "." , row [ "fext" ] );
	row [ '_DLM_name' ] = ds._DLM;
	row [ 'dl_link' ] = row.get ( 'mime', '' ); 
	row [ 'link_no_slash' ] = file_id_path.replace ( /^\//, "" ); 
	
	row [ 'file_options' ]  = ( dl_manager.get ( 'admin' ) ) ? String.formatDict ( dl_manager.templates [ 'file_options' ], row ) : String.formatDict ( dl_manager.templates [ 'file_options_user' ], row );
	row [ 'file_options_user' ]  = String.formatDict ( dl_manager.templates [ 'file_options_user' ], row );
	// convert files size
	row [ '_Size' ] = dl_manager._byte_conv ( row.get ( 'Size', 0 ) );
	// convert date fields
	row [ '_LastModified' ] = dl_manager._date_conv ( row.get ( 'LastModified' ) );
	row [ '_CreationTime' ] = dl_manager._date_conv ( row.get ( 'CreationTime' ) );
	row [ '_LastAccessed' ] = dl_manager._date_conv ( row.get ( 'LastAccessed' ) );
};

/* dl_manager.get_files ();
	params:
	- id_file: file id                                              SAFE_NUMBER
	- name:  Nome del file                                          SAFE_DB_STRING
	- descr:   Descrizione                                          SAFE_DB_STRING
	- module:   modulo                                              SAFE_DB_STRING
	- id_obj:   id_oggetto                                          SAFE_STRING
	- filters_tags: elenco tags                                     SAFE_DB_STRING
	- fext: estensione file                                         SAFE_DB_STRING
	- page_view: tipo di visualizzazione (icons,list,details)       SAFE_DB_STRING
	- order_by: order by ( name, ext, created ) name default        SAFE_DB_STRING
	- start_point:                                                  SAFE_NUMBER
	- limit:                                                        SAFE_NUMBER
	search files and return results
*/
dl_manager.get_files = function ( params, cback ) 
{
	params [ 'action' ] = 'dl_manager.ajax.get_files';
	dl_manager.ajax ( params, function ( data )
		{
			var res = [];
			if ( data.get ( 'results' ) ) res = data.results;
			if ( cback ) cback ( res );
		} );
};

/* dl_manager.browse_files ();
	param: params ( dict )		params for search
	return: nothing
	query database with searching criteria and render results
*/
dl_manager.browse_files = function ( name, vals )
{	

	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;	
	if ( ! vals ) vals = {};
	var dest_div = vals.get ( 'dest_div', inst._results_div );
	// get all values from filter form and use it as condition
	var frm = liwe.form.get ( inst.filter_form_name );
	if ( frm )
	{
		vals.inherits ( frm.get_values() );
	} else {
		//fix: params and form field names are differente
		vals [ 'page_view' ] = vals.get ( 'view' );
	}

	// store params
	inst.browse_files_params = vals;
	var frm_opts = liwe.form.get ( inst.browse_option_form );
	if ( frm_opts )
	{
		var opts = frm_opts.get_values();
		inst.browse_options [ 'page_view' ]  = opts [ 'page_view' ];
		inst.browse_options [ 'order_by' ]   = opts [ 'order_by' ];
		inst.browse_options [ 'pagination' ] = opts [ 'pagination' ];
	}	
	dl_manager.set_ds_templates ( name );
	// call ajax.py function for db query
	if ( ! vals.get ( 'action' ) ) vals [ 'action' ] = 'dl_manager.ajax.browse_files';
	inst.ds.set_fields ( vals );
	inst.ds.fill ( function () { inst.ds.render ( dest_div ); } ); 
};

/* dl_manager.dl_box ()
	param: params ( object )	filter params 
	param: dest_div ( string ) 	render div
	param: module ( string ) 	module name 
	param: view ( string ) 		list/icon/detail
	param: tmpl ( string ) 		template to use
	
	return html of search result to destination div
	NOTE: you can pass dataset cbacks trough params { 'ds_cback' : { 'fill_end' : 'my.function' } }
*/
dl_manager.dl_box = function ( name, params )
{
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) 
		dl_manager.init_instance ( name, params ); 
	//set custom cbacks to dataset
	if ( params.get ( 'ds_cback' ) )
		dl_manager.set_ds_cback ( name, params [ 'ds_cback' ] );
        dl_manager.browse_files ( name, params );
};

dl_manager.plugin = function ( el, params )
{
	if ( ! params.get ( 'inst' ) ) params.inst = 'jconed' + params.get ( 'id_obj', '' );
	dl_manager.dl_box ( null, params, el ); // , module, view, tmpl )
};

dl_manager.set_ds_cbacks = function ( name, params )
{
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;
	params.iterate ( function ( func, cback )
		{
			inst.ds.cbacks [ cback ] = func;
		} );
};

/* dl_manager.image_click ()
	param: name 		instance name
	param: id_file
	param: path
	call download file method or custom function ( imag_click );
*/
dl_manager.image_click = function ( name, id_file, path )
{
	var inst = dl_manager.get_instance ( name );
	if ( ! inst ) return;
	if (! inst.cbacks [ 'image_click' ] ) 
	{
		dl_manager.download_file ( id_file, path );
		return;
	}
	inst.cbacks [ 'image_click' ] ( id_file, path );
};

/* dl_manager.file_details ()
	param: file_path ( string )	complete file path
	param: id ( string )		file id
	return: nothing
	it sets gloabl var _temp_details with file details
*/
dl_manager.file_details = function ( file_path, id )
{
	var vals = { "action" : "dl_manager.ajax.file_details", "path_name" : file_path, "id_file": id };
	dl_manager.ajax ( vals, function ( data )
		{
			if ( data [ 'details' ] )
			{
				//console.debug ( data [ 'details' ] );
				data [ 'details' ][ 'Size' ] = dl_manager._byte_conv ( data [ 'details' ][ 'Size' ] );
				data [ 'details' ][ 'file_name' ] = String.basename ( file_path ); 
				liwe.utils.notifier.show ( String.formatDict ( dl_manager.templates [ 'details-box' ], data [ 'details' ] ), 'info' );
				dl_manager._temp_details = data [ 'details' ];
			}
		} );
};

dl_manager.init = function ()
{
	dl_manager.load_templates ();
};

/* -------------- generic functions ---------------------*/
/* dl_manager._byte_conv ()
	param: bytes ( decimal )	file size in bytes
	return: result ( string ) 	string with converted file size
*/
dl_manager._byte_conv = function ( bytes )
{
	var conv = "Bytes"; 
	var coef = 1;
	if ( bytes > 1024 ) 
		{ 
		  conv = "Kb";
		  coef =  1024; 
		}
	if ( bytes > 1048576 ) 
		{ 
		  conv = "Mb" 
		  coef =  1048576; 
		}
	return  result = String.format ( "%d %s" , Math.round ( bytes / coef ) , conv );
};
/* dl_manager._date_conv ()
	param: date_str ( string )	date in string format
	return: frm_d ( string ) 	formatted date in string format
*/
dl_manager._date_conv = function ( date_str, no_dbl_digit )
{
	if ( ! date_str ) return '0000 00:00';
	if ( no_dbl_digit ) Date.double_digit = false;
	return Date.formatted ( "%Y-%m-%d %H:%M", date_str );
	/*
	var d = new Date ( date_str );
	// FIXME : date2str non converte correttamente questo formato di data
	var temp_d = String.format ( "%s-%s-%s" , d.getFullYear (), (d.getMonth () + 1 ), d.getDate () );//liwe.utils.date2str ( d, 1 );
	var temp_h = d.getHours();
	temp_h = ( temp_h < 10 ) ? '0' + temp_h : temp_h ;
	var temp_m = d.getMinutes();
	temp_m = ( temp_m < 10 ) ? '0' + temp_m : temp_m ;

	frm_d = String.format ( "%s %s:%s" , temp_d, temp_h, temp_m );
	return frm_d;
	*/
};

/* dl_manager._expand_tag_tree ();
	param: node 		tree node
	recursive function which creates tree nodes
*/
dl_manager._expand_tag_tree = function ( node )
{
	var vals = {
			action : "tags.ajax.get_relative_tags",
			module : "dl_manager", //dl_manager._module,
			id_site: 1,
			tags   : node.val
		   };
	count = 0;
	dl_manager.ajax ( vals , function ( v ) 
					{ 

						var tags = v [ "tags" ];
						tags.iterate ( function ( t )
						{
							t.id = count++;
							t.val = node.val + "|" + t.name;
							console.debug ( node.val + ' - ' + t.name );
							t.onclick = "dl_manager._get_node_val";
							t.text = String.formatDict ( dl_manager.templates [ 'DLM-tree-folder' ], t );
							t.folder = true;
						} );

						node.expand_done ( tags );
					} );
};

/* dl_manager._get_node_val ();
	param: tree_name 	tree instance name
	param: node_name 	node name
	param: id_obj 		id object
	param: module 		module name 
	pass node values to browse_files function
*/
dl_manager._get_node_val = function ( tree_name, node_name, id_obj, module )
{
	var tree = OS3Tree.instances [ tree_name ];
	var node = tree.nodes [ node_name ];

	dl_manager.browse_files ( '', node.val, id_obj, module );
};

/* dl_manager._tags_tree_res ();
	param: root		starting tags separated by pipe
	create tree nodes first level 
*/
dl_manager._tags_tree_res = function ( root )
{
	if ( !root ) return;

	var tree = new OS3Tree.instance ( "tags_tree" );
	tree.scrollbars = true;

	tree.expand_request = dl_manager._expand_tag_tree;
	var sel_tags = root.split ( '|');
	var tags = sel_tags; 
	var dct = {};
	tags.iterate ( function ( t, i ) 
	{
		var txt = String ( t );
		dct = { name : txt }; 
		tree.add_folder ( null, String.formatDict ( dl_manager.templates [ 'DM-tree-folder' ], dct ) , "node_" + i , txt, '' ); 
	} );

	tree.render ( "DLM-tags-results" );
};
